#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "convert.h"
#include <QDebug>
#include <QSettings>
#include <QFileInfo>
#include <QMessageBox>
#include <QMenu>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    initialize();
}

MainWindow::~MainWindow()
{
    delete ui;
    delete ise113;
}

void MainWindow::initialize()
{
    qDebug("MainWindow: initialize...");
    setWindowTitle(tr("TH-IC000-I 接口通信分机测试软件"));
//    this->ise113 = new TH_ISE113_I(this);
    this->ise113 = new TH_ISE113_I();
    this->timer.setInterval(2500);
    this->iter = this->command.begin();

    connect(ui->pushButton,&QPushButton::toggled,this,&MainWindow::on_pushButton_clicked);
    connect(ui->checkBox_LocalPort,&QCheckBox::clicked,this,&MainWindow::on_checkbox_localPort_clicked);
    connect(ui->lineEdit_remoteIP,&QLineEdit::editingFinished,this,&MainWindow::on_lineEdit_remoteIP_changed);
    connect(ui->checkBox_ise113,&QCheckBox::clicked,this,&MainWindow::on_checkbox_ise113_clicked);
    connect(ise113,&TH_ISE113_I::rejected,this,&MainWindow::on_checkbox_ise113_unchecked);
    connect(&timer,&QTimer::timeout,this,&MainWindow::on_timeout);
//    ui->checkBox_ise113->setContextMenuPolicy(Qt::CustomContextMenu);
    //    connect(ui->checkBox_ise113,&QCheckBox::customContextMenuRequested,this,&MainWindow::on_show_contextmenu);

    //从Cfg.ini配置文件中读取配置
    readConfig();

//    QByteArray ar = Convert::toByteArray("39 18 46 07 41 07 46 07 49 07 49 07 4a 07 47 07 47 23 46 23 47 23 46 23 43 23 42 23 44 23 c3 09 5a 00 41 18 45 07 4d 07 46 07 49 07 00 00 00 00 00 00 5c 23 58 23 60 23 5b 23 00 00 00 00 00 00 c3 09 00 00  3e 18 b8 07 b9 07 bb 07 bb 07 b6 07 bb 07 bb 07 2a 23 2e 23 2f 23 2d 23 2e 23 31 23 2d 23 c3 09 00 00  57 18 ba 07 b9 07 ba 07 b8 07 b6 07 b8 07 ba 07 34 23 28 23 24 23 29 23 27 23 1f 23 05 23 c3 09 00 00  47 18 b7 07 b3 07 b0 07 b2 07 bb 07 00 00 00 00 39 23 40 23 3a 23 3f 23 3b 23 00 00 00 00 c3 09 a7 00");
//    qDebug()<<ar;
//    ise113->setData(ar);
//    ise113->show();
}

void MainWindow::writeConfig()
{
    QSettings *write = new QSettings("cfg.ini",QSettings::IniFormat);
    write->setValue("UDP/RemoteIP",ui->lineEdit_remoteIP->text());
    write->setValue("UDP/RemotePort",ui->spinBox_remotePort->value());
    if(ui->checkBox_LocalPort->isChecked())
    {

        write->setValue("UDP/FixedLocalPort",true);
    }
    else
    {

        write->setValue("UDP/FixedLocalPort",false);
    }
    write->setValue("UDP/LocalPort",ui->spinBox_LocalPort->value());
    write->setValue("Other/Period",3);
    delete write;
}

void MainWindow::readConfig()
{
    QFileInfo file("./cfg.ini");

    if(file.exists()){
        QSettings *read = new QSettings("cfg.ini",QSettings::IniFormat);
        ui->lineEdit_remoteIP->setText(read->value("UDP/RemoteIP").toString());
        ui->spinBox_remotePort->setValue(read->value("UDP/RemotePort").toInt());
        bool temp = read->value("UDP/FixedLocalPort").toBool();
        ui->checkBox_LocalPort->clicked(temp);
        ui->checkBox_LocalPort->setChecked(temp);
        ui->spinBox_LocalPort->setValue(read->value("UDP/LocalPort").toInt());

        delete read;
    }
    else
    {
        qDebug()<<"cfg.ini 文件不存在！";
    }
}

void MainWindow::on_pushButton_clicked()
{
    if(!socket.isValid())
    {
        qDebug()<<socket.state();
        if(ui->checkBox_LocalPort->isChecked())
        {
            if(socket.bind(ui->spinBox_LocalPort->value()))
            {
                ui->textEdit->append(QString("UDPSocket 成功邦到本地端口: %1").arg(ui->spinBox_LocalPort->value()));
            }
            else
            {
                ui->textEdit->append(QString("UDPSocket 邦到本地端口: %1 时出错！").arg(ui->spinBox_LocalPort->value()));
                return;
            }
            qDebug()<<socket.state();
        }
        qDebug()<<socket.state();
        socket.connectToHost(QHostAddress(ui->lineEdit_remoteIP->text()),ui->spinBox_remotePort->value());
        ui->textEdit->append(QString("UDPSocket 跟分机建立连接"));
        //保存当前配置到cfg.ini文件
        writeConfig();

        ui->lineEdit_remoteIP->setEnabled(false);
        ui->spinBox_remotePort->setEnabled(false);
        ui->spinBox_LocalPort->setEnabled(false);
        ui->checkBox_LocalPort->setEnabled(false);
        ui->pushButton->setText(tr("断开连接"));

        ui->groupBox_2->setEnabled(true);

        qDebug()<<"开启定时器……";
        command.insert(Convert::toByteArray("01 02"));
        command.insert(Convert::toByteArray("01 03"));
        this->timer.start();
    }
    else
    {
        socket.close();
        ui->textEdit->append(tr("UDPSocket 跟分机断开连接"));

        ui->lineEdit_remoteIP->setEnabled(true);
        ui->spinBox_remotePort->setEnabled(true);
        ui->spinBox_LocalPort->setEnabled(true);
        ui->checkBox_LocalPort->setEnabled(true);
        ui->pushButton->setText(tr("连接分机"));

        ui->groupBox_2->setEnabled(false);

        qDebug()<<"关闭定时器……";
        this->timer.stop();
    }
}

void MainWindow::on_checkbox_localPort_clicked(bool checked)
{
    ui->spinBox_LocalPort->setEnabled(checked);
}

void MainWindow::on_lineEdit_remoteIP_changed()
{
    QHostAddress ip(ui->lineEdit_remoteIP->text());
    qDebug()<<ip;
    if(ip.isNull())
    {
        ui->pushButton->setEnabled(false);
        //        QToolTip::showText(QPoint(50,100),tr("输入的分机IP地址有误请重新输入！"),ui->lineEdit_remoteIP,QRect(0,0,100,200),1000);
        if(QMessageBox::Ok == QMessageBox::warning(this,"错误","输入的分机IP有误\n请重新输入"))
        {
            ui->lineEdit_remoteIP->setFocus();
        }
    }
    else
    {
        ui->pushButton->setEnabled(true);
        ui->lineEdit_remoteIP->setText(ip.toString());
    }
}

void MainWindow::on_checkbox_ise113_clicked()
{
    qDebug()<< QObject::sender()->objectName();
//    qDebug()<<((QCheckBox *)QObject::sender())->checkState();
    qDebug()<<qobject_cast<QCheckBox*>(QObject::sender())->checkState();

    if(ui->checkBox_ise113->isChecked())
    {
        this->ise113->show();
        command.insert(Convert::toByteArray("01 A4"));
    }
    else
    {
        command.remove(Convert::toByteArray("01 A4"));
        this->ise113->hide();
    }
}

void MainWindow::on_checkbox_ise113_unchecked()
{
    qDebug()<<"on_checkbox_ise113_unchecked";
    ui->checkBox_ise113->setChecked(false);
}

void MainWindow::on_timeout()
{
    qDebug()<<"定时器超时";
    qDebug()<<command;
//    qDebug()<< *iter;
//    if(iter != command.end())
//    {
//        qDebug()<<"iter ++";
//        ++iter;
//    }
//    else
//    {
//        qDebug()<<"iter 重置为开始";
//        iter = command.begin();
//    }
//    qDebug()<<*iter;
    for(iter = command.begin();iter != command.end();++iter)
    {
        qDebug()<<*iter;
    }
}
